package com.lei.leetcode;

import com.lei.datastructure.linkedlist.LinkedList;

/**
 * @Author LeiXiaoLei
 * @Date 2022/7/22 16:37
 * @Version 1.0
 */
public class S_203 {
    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        ListNode(int[] arr) {
            if (arr == null || arr.length == 0)
                throw new IllegalArgumentException("arr can not be empty!");
            this.val = arr[0];
            ListNode cur = this;
            for (int i = 0; i < arr.length; i++) {
                cur.next = new ListNode(arr[i]);
                cur = cur.next;
            }
        }

        @Override
        public String toString() {
            StringBuilder res = new StringBuilder();

            ListNode cur = this.next;
            while (cur != null) {
                res.append(cur.val).append("->");
                cur = cur.next;
            }
            res.append("NULL");
            return res.toString();
        }
    }

    public static ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) {
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }
        if (head == null) return null;
        ListNode prev = head;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;

            } else {
                prev = prev.next;
            }

        }
        return head;
    }

    public static ListNode removeElements2(ListNode head, int val) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;

            } else {
                prev = prev.next;
            }

        }
        return head;
    }

    public static ListNode removeElements3(ListNode head, int val) {
        if (head == null) return null;
        ListNode res = removeElements3(head.next, val);
        if (head.val == val)
            return res;
        else {
            head.next = res;
            return head;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 6, 3, 4, 5, 6};
        ListNode listNode = new ListNode(arr);
        System.out.println(listNode);
        ListNode listNode1 = removeElements3(listNode, 6);
        System.out.println(listNode1);
    }
}
